package com.htwy.core.controller;

import com.htwy.core.config.WebappConfig;
import com.htwy.core.model.Orgnazation;
import com.htwy.ext.BaseController;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import java.util.Date;

public class OrgnazationController extends BaseController<Orgnazation> {

    @Override
    protected Orgnazation dao() {
        return Orgnazation.dao;
    }

    @Override
    public boolean beforeSave(Orgnazation entity) {

        if(StrKit.isBlank(entity.getParentId())){
            renderJson(Ret.fail().set("msg","必须拥有父组织机构"));
            return false;
        }

        Orgnazation parent = dao().findById(entity.getParentId());
        if(parent == null){
            renderJson(Ret.fail().set("msg","必须拥有父组织机构"));
            return false;
        }


        if (StrKit.isBlank(entity.getUuid())) {
            entity.setCreateTime(new Date());
            entity.setCreator(getLogin().getUuid());
            entity.setChildrenCount(0);

        }

        if (entity.getSerial() == null){
            entity.setSerial(getNextSerial(entity.getParentId()));
        }

        String serialStr = String.valueOf(entity.getSerial());
        while (serialStr.length() < 3){
            serialStr = "0" + serialStr;
        }

        entity.setRoute(StrKit.equals(entity.getRank(), parent.getRank())? parent.getRoute().substring(0, parent.getRoute().length() - 1) + serialStr + WebappConfig.getOrgSplit(): parent.getRoute() + serialStr + WebappConfig.getOrgSplit());

        entity.setMender(getLogin().getUuid());
        entity.setModifyTime(new Date());
        return true;
    }

    @Override
    public boolean afterSave(Orgnazation entity) {
        dao().updateChildrenCount(entity.getParentId());
        return true;
    }

    private Integer getNextSerial(String parentId) {
        Integer maxSerial = dao().getMaxSerialByParentId(parentId);
        return maxSerial != null ? maxSerial + 1 : 1;
    }
}